
$(function(){
	$("select").each(function(){
		$(this).append("<option value=''>---请选择---</option>");
	});

	var basePath = $("#basePath").val();
	$.ajax({
		url: basePath + "base_info/ajax_un_pigeonhole_base_data",
		type: "GET",
		dataType: "json",
		success: function( datas ) {
			console.log(datas);
			init(datas);
			
		}
	});
	
	$("select[data-type='localDRGsRiskGroup']").each(function(){
		var options = "";
		options+="<option value='1'>1级</option>";
		options+="<option value='2'>2级</option>";
		options+="<option value='3'>3级</option>";
		options+="<option value='4'>4级</option>";
		options+="<option value='5'>5级</option>";
		
		$(this).append(options);
	});
	
	$("input[name='onlyId']").focus();
	
	$("input[name='onlyId']").keydown(function(e){
		if(e.keyCode == 13){
			var onlyId = $(this).val();
			if(onlyId.length > 2){
				queryBtnClick();
				$(this).val(null);
			}
			
		}
	});
	
});

function init(baseInfo){
	var medicalDepts = baseInfo['medicalDepts'];
	$("select[name='outHospitalDeptCode'],[name='outDeptCode']").each(function(){
		var options = "";
		for(var index in medicalDepts){
			var medicalDept = medicalDepts[index];
	    	options+="<option value='"+medicalDept.uniq_code+"'>"+medicalDept.label+"</option>"
	    } 
       $(this).append(options);
       
	});
	
	var outHospitalTypes = baseInfo['outHospitalTypes'];
	$("select[name='outHospitalTypeCode']").each(function(){
		var options = "";
		for(var index in outHospitalTypes){
			var outHospitalType = outHospitalTypes[index];
	    	options+="<option value='"+outHospitalType.uniq_code+"'>"+outHospitalType.label+"</option>"
	    } 
       $(this).append(options);
	});
}



/*点击查询按钮*/
function queryBtnClick(){
	$("input[name='currentPage']").val(1);
	queryFormSubmit();
}

/*提交查询*/
function queryFormSubmit(){
	var submitData = $('#queryForm').serialize();
	var basePath = $("#basePath").val();
	layer.load(1);
	$("#export_h").html("");
	clearPage();
	$.ajax({
		url: basePath + "drgs_manage/ajax_query_drgs_group",
		dataType: "json",
		data:submitData,
		success: function( data ) {
			var success = data['success'];
			if(success){
				
				var params = data['data'];
				var totalCounts = params['totalCounts'];
				if(totalCounts > 0){
					layer.msg("查询成功");
					$("#export_h").html("<input type='button' value='导出' onclick='exportToExcel()'/>");
					
					var records = params['datas'];
					addRows(records);
					var pageSize = params['pageSize'];
					var currentPage = params['currentPage'];
					initPage(parseInt(totalCounts),parseInt(pageSize),parseInt(currentPage));
				}else{
					layer.msg("查询结果为空");
				}
				
			}else{
				layer.msg("查询失败");
			}
			console.log(data);
			
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			if(XMLHttpRequest.status == 200){
				if(textStatus == 'parsererror'){
					layer.msg("登陆已过期，请重新登陆");
				}else{
					layer.msg("未知错误，请联系管理员");
				}
			}else if(XMLHttpRequest.status == 0){
				if(textStatus == 'error'){
					layer.msg("无法连接服务器，请检测网络");
				}else{
					layer.msg("未知错误，请联系管理员");
				}
			}else{
				layer.msg("未知错误，请联系管理员");
			}
		},
		complete:function(XMLHttpRequest, textStatus){
			layer.closeAll('loading');
			parent.document.getElementById("mainContent").height=document.body.scrollHeight + 50;
			$("input[name='onlyId']").focus();
		}
	});
	
};

/*添加列表行*/
function addRows(records){
	for(var index in records){
		var record = records[index];
		var add_content=$("#template_tr").clone();
		add_content.removeAttr("hidden");
		add_content.attr("id",record.visit_guid);
		add_content.find("span[class='only_id']").html(record.only_id);
		add_content.find("span[class='mr_id']").html(record.mr_id);
		add_content.find("span[class='visit_number']").html(record.visit_number);
		add_content.find("span[class='patient_name']").html(record.patient_name);
		add_content.find("span[class='id_number']").html(record.id_number);
		add_content.find("span[class='out_dept_name']").html(record.out_dept_name);
		add_content.find("span[class='out_hospital_date']").html(record.out_hospital_date_format);
		add_content.find("span[class='out_hospital_type_name']").html(record.out_hospital_type_name);
		add_content.find("span[class='quality_control_status_name']").html(record.quality_control_status_name);
		add_content.find("span[class='coding_status_name']").html(record.coding_status_name);
		var coding_status_code = record.coding_status_code;
		if(!(coding_status_code && coding_status_code=='BABM')){
			add_content.find("td[data-type='operate_td']").html(record.coding_status_name);
		}else{
			var tdHtml="<a class='operate' onclick='layerDRGsGroup(this)' title='DRGs分组'>DRGs分组</a>"
			add_content.find("td[data-type='operate_td']").html(tdHtml);
		}
		$("#query_show_table tbody").append(add_content);
    } 
	
}

/*清空列表和分页控件*/
function clearPage(){
	$("#template_tr").siblings("tr").remove();
	$("#page_plus").html("");
	$("#totalPage").html("0");
    $("#currentPage").html("0/0");
}

/*初始化分页控件*/
function initPage(totalCounts,pageSize,currentPage){
	 var visiblePages = 5;
	 var totalPages =  totalCounts%pageSize==0?(totalCounts/pageSize):(parseInt(totalCounts/pageSize)+1);
	 if(totalCounts < 1){
		$("#page_plus").html("");
		$("#totalPage").html("0");
        $("#currentPage").html("0/0");
	 }else{
		 $('#page_plus').jqPaginator({

	        totalCounts: totalCounts,
	        pageSize:pageSize,
	        visiblePages: visiblePages,
	        currentPage: currentPage,

	        first:'<li class="first"><a href="javascript:void(0);">首页</a></li>',
	        prev: '<li class="prev"><a href="javascript:void(0);">上一页</a></li>',
	        next: '<li class="next"><a href="javascript:void(0);">下一页</a></li>',
	        last: '<li class="last"><a href="javascript:void(0);">末页</a></li>',
	        page: '<li class="page"><a href="javascript:void(0);">{{page}}</a></li>',
	        onPageChange: function (num,type) {

	     		if(type !='init'){
	     			$("input[name='currentPage']").val(num);
	     			queryFormSubmit();
				}
	            $("#totalPage").html(totalCounts);
	            $("#currentPage").html(num+"/"+totalPages);
	        }
	    });
	 }
}

function pageIndexCoding(obj){
	var basePath = $("#basePath").val();
	 var content = $(obj).parent().parent();
	 var visitGuid = content.attr("id");
	window.open(basePath+'medical_record_coding/edit_index_info?visitGuid='+visitGuid);
}

function pageIndexShow(obj){
	var basePath = $("#basePath").val();
	 var content = $(obj).parent().parent();
	 var visitGuid = content.attr("id");
	window.open(basePath+'medical_record_coding/show_home_page_index?visitGuid='+visitGuid);
}


var layerIndex
function layerDRGsGroup(obj){
	var basePath = $("#basePath").val();
	var add_content=$("#layer_drgs_group_div").clone();
	var content=$(obj).parent().parent();
	var visitGuid = content.attr("id");
	add_content.find("form").attr("id","drgs_group_form");
	var title = "DRGs分组";
	$.ajax({
		url: basePath + "drgs_manage/ajax_query_drgs_group_by_id",
		dataType: "json",
		data:{visitGuid:visitGuid},
		success: function( data ) {
			var success = data['success'];
			if(success){
				
				var record = data['data'];
				layerIndex = layer.open({
					type : 1,
					title : title,
					skin : 'layui-layer-rim', //加上边框
					area : [ '620px', '420px' ], //宽高
					offset : '50px',
					content : add_content.html(),
					success : function(layero, index) {
						var localDRGsShow = null;
						if(record){
							if(record.localDRGsCode){
								localDRGsShow = record.localDRGsCode+"["+record.localDRGsName+"]";
							}
							$("#drgs_group_form input[name='whetherMDTCode'][value='2']").click();
							$("#drgs_group_form input[name='whetherMDTName']").val("否");
						}
						radioValue("whetherDRGsManageCode",record.whetherDRGsManageCode,"whetherDRGsManageName",record.whetherDRGsManageName);
						
						$("#drgs_group_form input[name='localDRGsShow']").val(localDRGsShow);
						$("#drgs_group_form input[name='localDRGsCode']").val(record.localDRGsCode);
						
						$("#drgs_group_form input[name='localDRGsName']").val(record.localDRGsName);
						
						
						$("#drgs_group_form input[name='localDRGsGroupWeight']").val(record.localDRGsGroupWeight);
						
						selectValue("localDRGsRiskGroupCode",record.localDRGsRiskGroupCode,"localDRGsRiskGroupName",record.localDRGsRiskGroupName);
						
						$("#drgs_group_form input[name='icuNumberOfDay']").val(record.icuNumberOfDay);
						
						$("#drgs_group_form input[name='useVentilatorNumberOfHour']").val(record.useVentilatorNumberOfHour);
						
						$("#drgs_group_form input[name='localDRGsGroupTotalWeight']").val(record.localDRGsGroupTotalWeight);
						
						radioValue("whetherMDTCode",record.whetherMDTCode,"whetherMDTName",record.whetherMDTName);
						
						/*selectValue("whetherDRGsManageCode",record.whetherDRGsManageCode,"whetherDRGsManageName",record.whetherDRGsManageName);
						
						selectValue("whetherDRGsManageCode",record.whetherDRGsManageCode,"whetherDRGsManageName",record.whetherDRGsManageName);
						
						selectValue("whetherDRGsManageCode",record.whetherDRGsManageCode,"whetherDRGsManageName",record.whetherDRGsManageName);
						
						selectValue("whetherDRGsManageCode",record.whetherDRGsManageCode,"whetherDRGsManageName",record.whetherDRGsManageName);
						*/
						
						$("#drgs_group_form input[name='visitGuid']").val(visitGuid);
						$("#drgs_group_form select").each(function() {
							$(this).change(function() {
								var eventObj = $(this);
								var nameObjName = eventObj.attr("name").replace("Code", "Name");

								if (eventObj.val() != "") {
									var name = eventObj.find("option:selected").text();
									eventObj.next("input[name='" + nameObjName + "']").val(name);
								} else {
									eventObj.next("input[name='" + nameObjName + "']").val("");
								}
							});
						});

						$("#drgs_group_form input[type='radio']").each(function() {
							$(this).click(function() {
								$(this).nextAll("input[name='" + $(this).attr("name").replace("Code", "Name") + "']").val($(this).attr("title"));
							});
							$(this).dblclick(function() {
								$(this).removeAttr("checked");
								$(this).nextAll("input[name='" + $(this).attr("name").replace("Code", "Name") + "']").val(null);
							});
						});
						
						$("#drgs_group_form input[name='localDRGsShow']").autocomplete({
							source: function( request, response ) {
								var eventObj = $(this.element);
								
								var codeObjName = eventObj.attr("name").replace("Show", "Code");
								eventObj.nextAll("input[name='"+codeObjName+"']").val("");
								
								var nameObjName = eventObj.attr("name").replace("Show", "Name");
								eventObj.nextAll("input[name='"+nameObjName+"']").val("");
								
								$.ajax({
									url: basePath + "base_info/ajax_drgs_group_by_query_name",
									dataType: "json",
									data:{
										queryName: request.term
									},
									success: function( data ) {
									response( $.map( data, function( item ) {
										return {
											label:item.uniq_code+'['+item.label+']',
											uniq_code:item.uniq_code,
											uniq_name:item.label,
											group_weight:item.group_weight
										}
									}));
								}
							});
							},
							minLength: 2,
							select: function( event, ui ) {
								var eventObj = $(this);
								var item = ui.item;
								var codeObjName = eventObj.attr("name").replace("Show", "Code");
								eventObj.nextAll("input[name='"+codeObjName+"']").val(item.uniq_code);
								
								var nameObjName = eventObj.attr("name").replace("Show", "Name");
								eventObj.nextAll("input[name='"+nameObjName+"']").val(item.uniq_name);
								if(item.group_weight){
									eventObj.parent().parent().find("input[name$='localDRGsGroupWeight']").val(item.group_weight);
									eventObj.parent().parent().find("input[name$='localDRGsGroupTotalWeight']").val(item.group_weight);
								}
							},search: function( event, ui ) {
								var eventObj = $(this);
								var codeObjName = eventObj.attr("name").replace("Show", "Code");
								eventObj.nextAll("input[name='"+codeObjName+"']").val(null);
								
								var nameObjName = eventObj.attr("name").replace("Show", "Name");
								eventObj.nextAll("input[name='"+nameObjName+"']").val(null);
								eventObj.parent().parent().find("input[name$='localDRGsGroupWeight']").val(null);
								eventObj.parent().parent().find("input[name$='localDRGsGroupTotalWeight']").val(null);
								
							}
						});
						
						var validator = $("#drgs_group_form").validate({
							errorElement: "title",
							submitHandler:function(){
								layerDRGsGroupSubmit();
							},
							rules:{
								localDRGsGroupWeight: {
									number:true,
					            	range:[0,99999999]
					            },
					            icuNumberOfDay: {
									number:true,
					            	range:[0,99999999]
					            },
					            useVentilatorNumberOfHour: {
									number:true,
					            	range:[0,99999999]
					            },
					            localDRGsGroupTotalWeight: {
									number:true,
					            	range:[0,99999999]
					            }
							}
						});
					}
				});
				
			}else{
				layer.msg("操作失败");
			}
			console.log(data);
			
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			if(XMLHttpRequest.status == 200){
				if(textStatus == 'parsererror'){
					layer.msg("登陆已过期，请重新登陆");
				}else{
					layer.msg("未知错误，请联系管理员");
				}
			}else if(XMLHttpRequest.status == 0){
				if(textStatus == 'error'){
					layer.msg("无法连接服务器，请检测网络");
				}else{
					layer.msg("未知错误，请联系管理员");
				}
			}else{
				layer.msg("未知错误，请联系管理员");
			}
		},
		complete:function(XMLHttpRequest, textStatus){
			layer.closeAll('loading');
			parent.document.getElementById("mainContent").height=document.body.scrollHeight + 50;
			$("input[name='onlyId']").focus();
		}
	});
	
}
function layerDRGsGroupClick(){
	$('#drgs_group_form').submit();
}

function layerDRGsGroupSubmit(){
	var submitData = $('#drgs_group_form').serialize();
	var basePath = $("#basePath").val();
	layer.load(1);
	$.ajax({
		url: basePath + "drgs_manage/ajax_edit_drgs_group",
		type: "POST",
		dataType: "json",
		data:submitData,
		success: function( data ) {
			var success = data['success'];
			if(success){
				var stateCode = data['stateCode'];
				if("1" == stateCode){
					layer.msg("DRGs分组成功！");
					layer.close(layerIndex);
				}else{
					layer.msg("DRGs分组失败！");
					
				}
			}else{
				layer.msg("操作错误，请重试！");
			}
			console.log(data);
			
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			if(XMLHttpRequest.status == 200){
				if(textStatus == 'parsererror'){
					layer.msg("登陆已过期，请重新登陆");
				}else{
					layer.msg("未知错误，请联系管理员");
				}
			}else if(XMLHttpRequest.status == 0){
				if(textStatus == 'error'){
					layer.msg("无法连接服务器，请检测网络");
				}else{
					layer.msg("未知错误，请联系管理员");
				}
			}else{
				layer.msg("未知错误，请联系管理员");
			}
		},
		complete:function(XMLHttpRequest, textStatus){
			layer.closeAll('loading');
		}
	});
}

function selectValue(codeName,codeValue,nameName,nameValue){
	if(codeValue){
	  	var selectedIndex = $("#drgs_group_form select[name='"+codeName+"'] option[value='"+codeValue+"']").first().index();
		if (selectedIndex == -1) {
			var option = "<option selected value='" + codeValue + "'>" + nameValue + "</option>";
			$("#drgs_group_form select[name='"+codeName+"']").append(option);
		} else {
			$("#drgs_group_form select[name='"+codeName+"']").get(0).selectedIndex = selectedIndex;
		}
	}
	$("#drgs_group_form select[name='"+codeName+"']").next("input[name='"+nameName+"']").val(nameValue);
}

function radioValue(codeName,codeValue,nameName,nameValue){
	if(codeValue){
		$("#drgs_group_form input[name='"+codeName+"'][value='"+codeValue+"']").attr("checked",true);
	}
	$("#drgs_group_form input[name='"+nameName+"']").val(nameValue);
}
function exportToExcel(){
	var basePath = $("#basePath").val();
	$("#queryForm").attr("action",basePath+"drgs_manage/drgs_export_excel");
	$("#queryForm").submit();
}